package com.longcai.cm.utils.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author libingxing
 */
public class SmsClient {

    public static String sendMsg(String mobile, String code) {

        Map<String, String> param = new HashMap<>(1);
        param.put("code", code);
        return sendMsg(mobile, param, SmsTemplate.LOGIN_TEMPLATE);
    }

    public static String sendMsg(
            String mobile, Map<String, String> param, String templateCode
    ) {
        DefaultProfile profile = DefaultProfile.getProfile(SmsConfig.REGION_ID, SmsConfig.ACCESS_KEY, SmsConfig.SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(SmsConfig.DOMAIN);
        request.setSysVersion(SmsConfig.VERSION);
        request.setSysAction(SmsConfig.ACTION);
//        节点
        request.putQueryParameter("PhoneNumbers", mobile);
//        签名
        request.putQueryParameter("SignName", SmsConfig.SIGN_NAME);
//        模板id
        request.putQueryParameter("TemplateCode", templateCode);
//        模板参数信息
        final String paramString = JSON.toJSONString(param);
        if (StringUtils.isNotBlank(paramString)) {
            request.putQueryParameter("TemplateParam", paramString);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.isNotBlank(data)) {
                AliSmsReturn smsReturn = JSON.parseObject(data, AliSmsReturn.class);
                if (SmsConfig.SUCCESS_CODE.equals(smsReturn.getCode())) {
                    return "";
                } else {
                    return smsReturn.getMessage();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        System.err.println(sendMsg("18734890165", "030200"));
    }

}
